package com.helasasa.maxfunds.lineofcredit.cashloan.ghana.user

import androidx.appcompat.app.AppCompatActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.disbursing.DisbursingGhanaActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.loan.LoanConfirmGhanaActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.proof.ProofGhanaActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.proof.face.ProofGhanaFaceActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.proof.ocr.ProofGhanaOcrActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.proof.wallet.ProofGhanaWalletActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.reject.RejectGhanaActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.review.ReviewGhanaActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.risking.RiskingGhanaActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.selectapply.SelectApplyGhanaActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.tabhome.TabHomeGhanaActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.tabrepay.TabRepayGhanaActivity
import org.json.JSONArray
import org.json.JSONObject

/**
 * 流程状态
 */
data class MainProcessResult(
    val isLending: Boolean? = false,
    val isRepayNow: Boolean? = false,
    val isReject: Boolean? = false,
    val isReview: Boolean? = false,
    val isProof: Boolean? = false,
    val isProofOcr: Boolean? = false,
    val isProofFace: Boolean? = false,
    val isProofWallet: Boolean? = false,
    val isCanApply: Boolean? = false,
    val nextRouter: Class<out AppCompatActivity>? = null
)

/**
 * 判断用户状态
 *
 * @param from 从哪来 tab_home, proof
 */
fun JSONObject.mainProcessFormat(
    fromTabHome: Boolean? = null,
    fromProof: Boolean? = null,
    fromRepayDetail: Boolean? = null,
    fromCreateLoan: Boolean? = null,
    fromMyProfile: Boolean? = null,
    fromTabRepay: Boolean? = null
): MainProcessResult {
    // 订单状态
    val orderStatus = this.optString("orderStatus")
    val applyStatus = this.optString("applyStatus")

    // 订单是否处于放款中
    val isLending = (orderStatus == "CREATED") or (orderStatus == "LENDING")

    // 订单是否处于还款中
    val isRepayNow =
        (orderStatus == "LOANED") or (orderStatus == "OVERDUE") or (orderStatus == "BAD_DEBT")

    // 订单是否被拒绝
    val isOrderReject = (orderStatus == "DENIED")
    val isApplyReject =
        (applyStatus == "SYS_DENIED") or (applyStatus == "MANU_DENIED") or (applyStatus == "DS_DENIED")

    val isReject = isApplyReject or isOrderReject

    // 订单是否在审核中
    val isReview = (applyStatus == "CREATED") or (applyStatus == "SYS_CHECK") or
            (applyStatus == "SYS_APROVAL") or (applyStatus == "MANU_APROVAL") or (applyStatus == "DS_APROVAL")

    // 是否需要走认证
    val steps = this.optJSONArray("steps") ?: JSONArray()

    val isProof = steps.length() > 0
    var isProofOcr = false
    var isProofFace = false
    var isProofWallet = false

    // 是否已提交资料，通过风控
    val isRiskPass = this.optString("canApply") == "YES"

    // 具体认证步骤
    if (isProof) {
        val nextStep = steps[0] as String
        val nextStepObject = this.optJSONObject(nextStep)
        if (nextStepObject == null) {
            if (nextStep.contains("ocr_", true)) {
                isProofOcr = true

            } else if (nextStep.contains("wallet_", true)) {
                isProofWallet = true

            } else if (nextStep.contains("account_", true)) {
                isProofWallet = true

            } else if (nextStep.contains("selfie_", true)) {
                isProofFace = true
            }
        }
    }

    // 是否可以申请贷款
    val isCanApply = this.optString("canApply") == "YES"

    // 关联router
    var nextRouter: Class<out AppCompatActivity>? = null
    nextRouter = if (isRiskPass) {
        TabRepayGhanaActivity::class.java
    } else {
        TabHomeGhanaActivity::class.java
    }

    // 如果是认证步骤
    if (fromProof == true) {
        nextRouter = if (isProof) {
            if (isProofOcr) {
                ProofGhanaOcrActivity::class.java
            } else if (isProofFace) {
                ProofGhanaFaceActivity::class.java
            }  else if (isProofWallet) {
                ProofGhanaWalletActivity::class.java
            }else {
                ProofGhanaActivity::class.java
            }
        } else {
            RiskingGhanaActivity::class.java
        }
    }

    // 如果是认证步骤
    if (fromMyProfile == true) {
        nextRouter = if (isReview) {
            ReviewGhanaActivity::class.java
        } else if (isReject) {
            RejectGhanaActivity::class.java
        } else if (isLending) {
            DisbursingGhanaActivity::class.java
        } else if (isProofOcr) {
            ProofGhanaOcrActivity::class.java
        } else if (isProofFace) {
            ProofGhanaFaceActivity::class.java
        } else if (isProofWallet) {
            ProofGhanaWalletActivity::class.java
        } else if (isProof) {
            ProofGhanaActivity::class.java
        } else {
            LoanConfirmGhanaActivity::class.java
        }
    }

    // 如果是还款详情步骤
    if (fromRepayDetail == true) {
        nextRouter = if (!isRepayNow) {
            TabRepayGhanaActivity::class.java
        } else {
            null
        }
    }

    // 如果是创建订单步骤
    if (fromCreateLoan == true) {
        nextRouter = if (isReview) {
            ReviewGhanaActivity::class.java
        } else if (isReject) {
            RejectGhanaActivity::class.java
        } else if (isLending) {
            DisbursingGhanaActivity::class.java
        } else if (isRepayNow) {
            TabRepayGhanaActivity::class.java
        } else {
            null
        }
    }

    // 如果是未完成认证首页步骤
    if (fromTabHome == true) {
        nextRouter = if (isCanApply) {
            TabRepayGhanaActivity::class.java
        } else {
            SelectApplyGhanaActivity::class.java
        }
    }

    // 如果是已完成认证首页步骤
    if (fromTabRepay == true) {
        nextRouter = if (isReview) {
            ReviewGhanaActivity::class.java
        } else if (isReject) {
            RejectGhanaActivity::class.java
        } else if (isLending) {
            DisbursingGhanaActivity::class.java
        } else if (isCanApply) {
            LoanConfirmGhanaActivity::class.java
        } else if (isProofOcr) {
            ProofGhanaOcrActivity::class.java
        } else if (isProofFace) {
            ProofGhanaFaceActivity::class.java
        }else if (isProofWallet) {
            ProofGhanaWalletActivity::class.java
        }  else if (isProof) {
            ProofGhanaActivity::class.java
        } else {
            LoanConfirmGhanaActivity::class.java
        }
    }

    return MainProcessResult(
        isLending = isLending,
        isRepayNow = isRepayNow,
        isReject = isReject,
        isReview = isReview,
        isProof = isProof,
        isProofOcr = isProofOcr,
        isProofFace = isProofFace,
        isProofWallet = isProofWallet,
        isCanApply = isCanApply,
        nextRouter = nextRouter
    )
}

/**
 * 获取当前待做步骤
 */
fun JSONObject.nextRender(): HashMap<String, Any> {
    val renderResult = HashMap<String, Any>()
    val renderList = mutableListOf<JSONObject>()

    // 是否需要走认证
    val steps = this.optJSONArray("steps") ?: JSONArray()
    val allSteps = this.optJSONArray("allSteps") ?: JSONArray()
    val allStepTitles = this.optJSONArray("allStepTitles") ?: JSONArray()
    if (steps.length() > 0) {
        val nextStep = steps[0] as String
        renderResult["step"] = nextStep

        // page title
        var pageTitleIndex = -1
        for (pi in 0 until allSteps.length()) {
            val allStep = (allSteps[pi] as String)
            if (allStep.equals(nextStep, true)) {
                pageTitleIndex = pi
                break
            }
        }
        // 页面标头进度
        if (allStepTitles.length() > pageTitleIndex) {
            renderResult["pageTitle"] = (allStepTitles[pageTitleIndex] as String)

            // 标头
            val headers = mutableListOf<JSONObject>()
            for (hi in 0 until allStepTitles.length()) {
                headers.add(
                    JSONObject().apply {
                        put("title", allStepTitles[hi] as String)
                        put("done", (hi <= pageTitleIndex))
                    }
                )
            }
            renderResult["headers"] = headers
        }

        val nextStepObject = this.optJSONObject(nextStep)
        if (nextStepObject != null) {
            // 获取list
            val apiUrl = nextStepObject.optString("apiUrl")
            renderResult["apiUrl"] = apiUrl
            if (apiUrl.isNotBlank()) {
                // 判断是否为联系人
                val isContact = nextStepObject.optString("isContact").equals("YES", true)
                if (isContact) {
                    // 格式化relationship，保证数组对齐
                    val contactParamName = nextStepObject.optString("contactParamName")
                    val relationShips = nextStepObject.optJSONArray("relationShips") ?: JSONArray()
                    val contactCount = nextStepObject.optInt("itemCount")
                    if (relationShips.length() < contactCount) {
                        val needAddCount = contactCount - relationShips.length()
                        for (ni in 0 until needAddCount) {
                            relationShips.put(JSONArray().apply {
                                put("Couple")
                                put("Father")
                                put("Mother")
                            })
                        }
                    }
                    val relationShipsFormat = JSONArray()
                    for (rsi in 0 until relationShips.length()) {
                        val rsiArray = relationShips[rsi] as JSONArray
                        val rsiFormat = JSONArray()
                        for (rsfi in 0 until rsiArray.length()) {
                            val rsfitem = rsiArray[rsfi]
                            rsiFormat.put(JSONObject().apply {
                                put("title", rsfitem)
                                put("value", rsfitem)
                            })
                        }
                        relationShipsFormat.put(rsiFormat)
                    }

                    for (i in 0 until contactCount) {
                        val dataList = nextStepObject.optJSONArray("dataList") ?: JSONArray()
                        val arrayZone = JSONArray()
                        for (di in 0 until dataList.length()) {
                            val dataItem = dataList[di] as JSONObject

                            // 深拷贝行对象
                            val itemKeys = dataItem.keys()
                            val itemZone = JSONObject()
                            for (ikey in itemKeys) {
                                itemZone.put(ikey, dataItem.optString(ikey))
                            }
                            val action = itemZone.optString("action")
                            if (action.equals("CONTACT_GROUP_RELATION", true)) {
                                // 更改类型
                                itemZone.put("actionOld", "CONTACT_GROUP_RELATION")
                                itemZone.put("action", "SELECT")

                                // 更新列表
                                val relation = relationShipsFormat[di]
                                itemZone.put("values", relation)

                            } else if (action.equals("CONTACT_GROUP_NAME", true)) {
                                // 更改类型
                                itemZone.put("actionOld", "CONTACT_GROUP_NAME")
                                itemZone.put("action", "INPUT")

                            } else if (action.equals("CONTACT_GROUP_PHONE", true)) {
                                // 更改类型
                                itemZone.put("actionOld", "CONTACT_GROUP_PHONE")
                                itemZone.put("action", "INPUT")
                            }

                            // 渲染url
                            itemZone.put("apiUrl", apiUrl)

                            // 渲染值
                            itemZone.put("content", "")
                            itemZone.put("realContent", "")
                            arrayZone.put(itemZone)
                        }

                        // 组装group contact
                        val groupDataItem = JSONObject()
                        groupDataItem.apply {
                            // action
                            put("action", "CONTACT_GROUP")

                            // 类型
                            put("viewType", 3)

                            // 标题
                            put("title", "Contact ${i + 1}")

                            // 渲染url
                            put("apiUrl", apiUrl)

                            // 渲染url 参数名称
                            put("paramName", contactParamName)

                            // 渲染列表
                            put("dataList", arrayZone)
                        }

                        println("======= groupDataItem start")
                        println(groupDataItem)
                        println("======= groupDataItem end")

                        // 增加渲染行
                        renderList.add(groupDataItem)
                    }
                } else {
                    val dataList = nextStepObject.optJSONArray("dataList") ?: JSONArray()
                    for (i in 0 until dataList.length()) {
                        val dataItem = dataList[i] as JSONObject
                        val action = dataItem.optString("action")
                        if (action.equals("INPUT", true)) {
                            dataItem.put("viewType", 0)
                        } else if (action.equals("SELECT", true)) {
                            dataItem.put("viewType", 1)
                        } else if (action.equals("DATE_PICK", true)) {
                            dataItem.put("viewType", 2)
                        } else {
                            dataItem.put("viewType", 0)
                        }

                        // 渲染url
                        dataItem.put("apiUrl", apiUrl)

                        // 渲染值
                        dataItem.put("content", "")

                        // 增加渲染行
                        renderList.add(dataItem)
                    }
                }
            }
        } else {
            if (nextStep.contains("ocr_", true)) {
                renderResult["needOcr"] = true

            } else if (nextStep.contains("wallet_", true)) {
                renderResult["needWallet"] = true

            } else if (nextStep.contains("account_", true)) {
                renderResult["needWallet"] = true

            } else if (nextStep.contains("selfie_", true)) {
                renderResult["needFace"] = true
            }
        }
    }

    println("==========页面渲染============")
    println(renderList)

    renderResult["dataList"] = renderList

    return renderResult
}